package antidestiny.java2dex.ui.activity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;

import antidestiny.java2dex.Jing;
import antidestiny.java2dex.R;
import antidestiny.java2dex.compiler.Compiler;
import antidestiny.utilib.Aide;
import antidestiny.utilib.io.FileUtils;
import antidestiny.utilib.ui.fragment.explorer.ExplorerFileFilter;
import antidestiny.utilib.ui.fragment.explorer.ExplorerFragment;
import antidestiny.utilib.ui.fragment.explorer.ExplorerManagerI;
import antidestiny.utilib.ui.fragment.explorer.FileItem;
import dalvik.system.DexFile;

public class CompileActivity extends AppCompatActivity implements ExplorerManagerI {
    ViewGroup layoutOptions;
    ViewGroup layoutRoot;
    ExplorerFragment explorerFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compile);
        Aide.tryDebug(this);
        SharedPreferences sharedPreferences = getSharedPreferences(Jing.COMPILER_PREFERENCE, MODE_PRIVATE);
        setOutputText(sharedPreferences.getString(Jing.PREF_OUTPUT_TEXT, Environment.getExternalStorageDirectory() + "/output"));
        setSourceText(sharedPreferences.getString(Jing.PREF_SOURCE_TEXT, ""));
        setLibText(sharedPreferences.getString(Jing.PREF_LIB_TEXT, ""));
        checkRtJar();

        layoutOptions = (ViewGroup) findViewById(R.id.layout_options);
        layoutRoot = (ViewGroup) findViewById(R.id.layout_root);

        File dir = Environment.getExternalStorageDirectory();
        File dirParent = dir.getParentFile();
        if (!dirParent.canRead() || dirParent == null) dirParent = dir;//安卓6中sdcard的上一层不可读
        explorerFragment = ExplorerFragment.newInstance(dir, dirParent, this);
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

        fragmentTransaction.replace(R.id.to_be_replaced, explorerFragment);
        fragmentTransaction.hide(explorerFragment);
        fragmentTransaction.commit();
    }

    /**
     * rt.jar是java必须的
     */
    void checkRtJar() {
        File dir = getFilesDir();
        String[] files = dir.list();
        boolean rtExists = false;
        if (files != null)
            for (String file : files) {
                if (file.equals("rt.jar"))
                    rtExists = true;
            }
        if (!rtExists) {
            Aide.t("rt不存在，试着创建");
            try {
                byte[] bytes = FileUtils.read(getAssets().open("rt.jar"));
                FileUtils.write(new File(dir.getAbsolutePath() + "/rt.jar"), bytes);
            } catch (IOException e) {
                e.printStackTrace();
                warningToast(e.toString());
            }

        } else {
            Aide.t("rtjar存在，位置是：" + dir);
        }
    }

    public void onClick(View v) {
        Aide.t("点击:" + v);
        switch (v.getId()) {
            //选择源文件所在的目录
            case R.id.choose_src:
                chooseFile(CHOOSE_JAVA_PROJECT_DIR);
                break;
            case R.id.choose_lib:
                chooseFile(CHOOSE_LIB);
                break;
            case R.id.choose_output:
                chooseFile(CHOOSE_OUTPUT_DIR);
                break;
            case R.id.build:
                build();
                break;
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (explorerFragment != null && explorerFragment.isVisible()) {
                    explorerFragment.back();
                    return true;
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    final int CHOOSE_JAVA_PROJECT_DIR = 1;
    final int CHOOSE_OUTPUT_DIR = 2;
    final int CHOOSE_LIB = 4;

    void chooseFile(int request) {
        layoutOptions.setVisibility(View.GONE);
        getSupportFragmentManager().beginTransaction()
                .show(explorerFragment).commit();
        switch (request) {
            case CHOOSE_JAVA_PROJECT_DIR:
                explorerFragment.chooseRequest(request, ExplorerFileFilter.TYPE_DIR_ONLY, null, null);
                break;
            case CHOOSE_LIB:
                explorerFragment.chooseRequest(request, ExplorerFileFilter.SPECIFIC_FILE_TYPE, "jar", null);
                break;
            case CHOOSE_OUTPUT_DIR:
                explorerFragment.chooseRequest(request, ExplorerFileFilter.TYPE_DIR_ONLY, null, null);
                break;
        }


    }


    @Override
    public void onChooseResult(int request, List<FileItem> items) {
        layoutOptions.setVisibility(View.VISIBLE);
        getSupportFragmentManager().beginTransaction().hide(explorerFragment).commit();
        if (items != null)
            switch (request) {
                case CHOOSE_JAVA_PROJECT_DIR:
                    if (items.size() > 1) warningToast(getString(R.string.filecount_out_of_limit));

                    EditText srcEdit = (EditText) findViewById(R.id.src);
                    srcEdit.setText(items.get(0).path);
                    break;
                case CHOOSE_LIB:
                    StringBuffer buffer = new StringBuffer();
                    for (int i = 0; i < items.size(); i++) {
                        buffer.append(items.get(i).path);
                        if (i < items.size() - 1) buffer.append(Jing.DIFFRENT_FILE_SEPRATOR);
                    }
                    EditText libChoose = (EditText) findViewById(R.id.lib);
                    libChoose.setText(buffer.toString());
                    break;
                case CHOOSE_OUTPUT_DIR:
                    if (items.size() > 1)
                        warningToast(getString(R.string.filecount_out_of_limit));
                    EditText outputEdit = (EditText) findViewById(R.id.editText_output);
                    outputEdit.setText(items.get(0).path);
                    break;

            }
    }

    @Override
    public void onPasteBoardChange(@Nullable File file) {

    }

    void warningToast(String s) {
        Toast.makeText(this, s, Toast.LENGTH_LONG).show();
    }

    EditText getOutputEdit() {
        return (EditText) findViewById(R.id.editText_output);
    }

    EditText getSourceDirEdit() {
        return (EditText) findViewById(R.id.src);
    }

    EditText getLibEdit() {
        return (EditText) findViewById(R.id.lib);
    }

    String getSourceText() {
        return ((EditText) findViewById(R.id.src)).getText().toString();
    }

    String getLibMessage() {
        return ((EditText) findViewById(R.id.lib)).getText().toString();
    }

    String getOutputText() {
        return getOutputEdit().getText().toString();
    }

    void setOutputText(String t) {
        getOutputEdit().setText(t);
    }

    void setSourceText(CharSequence cs) {
        getSourceDirEdit().setText(cs);
    }

    void setLibText(CharSequence cs) {
        getLibEdit().setText(cs);
    }

    void build() {
        File javaProjectDir = new File(((EditText) findViewById(R.id.src)).getText().toString());
        File outputDir = new File(((EditText) findViewById(R.id.editText_output)).getText().toString());
        String libMessage = ((EditText) findViewById(R.id.lib)).getText().toString();
        String outputFileName = ((EditText) findViewById(R.id.outputFileName)).getText().toString();
        antidestiny.java2dex.compiler.Compiler compiler = new Compiler(javaProjectDir, libMessage, outputDir, outputFileName, this);
        compiler.compile();

        SharedPreferences sharedPreferences = getSharedPreferences(Jing.COMPILER_PREFERENCE, MODE_PRIVATE);
        sharedPreferences.edit().putString(Jing.PREF_SOURCE_TEXT
                , getSourceText())
                .putString(Jing.PREF_LIB_TEXT, getLibMessage())
                .putString(Jing.PREF_OUTPUT_TEXT, getOutputText()).apply();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (Aide.debugging()) {
            menu.add("调试按钮")
                    .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem item) {
                            try {
                                DexFile file = new DexFile("/sdcard/output/classes.jar");
                                Enumeration<String> entries = file.entries();
                                while (entries.hasMoreElements()) {
                                    Aide.t(entries.nextElement());
                                    //  Class<?> clz=file.loadClass(entries.nextElement(), getClassLoader());
                                    //   clz.getMethods();
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                            return true;
                        }
                    });
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        return super.onMenuOpened(featureId, menu);
    }

}
